package com.chzu.config.security;

import com.chzu.config.security.contents.SecurityContents;
import com.chzu.config.security.filter.JwtAuthenticationFilter;
import com.chzu.config.security.handler.JwtAccessDeniedHandler;
import com.chzu.config.security.handler.JwtAuthenticationEntryPoint;
import com.chzu.config.security.service.UserDetailServiceImpl;
import com.chzu.pojo.SysUser;
import com.chzu.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author lz
 * @Version 1.0
 * @Company 滁州大健康与养老产业研究院
 * @ClassName SecurityConfig
 * @Description TODO
 * @Date 2022/01/27 17:17
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceImpl userDetailService;
    @Autowired
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;


    /**
     * 实现自定义登录逻辑
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置白名单
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .mvcMatchers(SecurityContents.NONE_SECURITY_URL_PATTERNS);
    }

    /**
     * security核心配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用jwt，关闭csrf
        http.csrf().disable();
        //基于token认证，关闭session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //配置白名单  除白名单以外的都进行认证
        http.authorizeRequests().anyRequest().authenticated();
        //禁用缓存
        http.headers().cacheControl();
        //添加jwt登录授权的过滤器
        http.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加未授权和未登录的返回结果
        http.exceptionHandling().accessDeniedHandler(jwtAccessDeniedHandler).authenticationEntryPoint(jwtAuthenticationEntryPoint);
    }

//    /** 这里因为mapper查询roles的原因，必须先调用userService.findByUsername这个方法*用这种实现会导致调用方法迟于上面方法，导致角色信息为空
    //    所以这里采用实现UserDetailSerce中loadUserByUserName形式
//     * 重写WebSecurityConfigurerAdapter下的userDetailsService
//     * 实现自定义的登录
//     * @return
//     */
//    @Override
//    @Bean
//    public UserDetailsService userDetailsService() {
//        return username -> {
//            SysUser user = userService.findByUsername(username);
//            if (user != null) {
//                return user;
//            }
//            throw new UsernameNotFoundException("用户名或密码错误");
//        };
//    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public JwtAuthenticationFilter authenticationFilter() {
        return new JwtAuthenticationFilter();
    }
}
